package userManagement;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

import db.DatabaseConnector;
import java.math.BigInteger;
import java.security.MessageDigest;

public class UserEdited extends HttpServlet {
	public void doPost(HttpServletRequest request,HttpServletResponse response)
										throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		DatabaseConnector DBConnect = new DatabaseConnector(DatabaseConnector.getDatabaseType());


		out.println("<html><head><title>User Modification -- Result</title>");
		out.println("<script type=\"text/javascript\" src=\"../userManager.js\"></script>");
		out.println("</head><body>");


		String[] in = {"*"};
		Object[] check = DBConnect.selectSQL("USERS",in,"username",request.getParameter("username")); // Retrieve connection information
		try{
			if (check[0].equals("null")){ }//triggers catch if does not exist => username changed
			if (!request.getParameter("username").equals(request.getParameter("oldUsername"))){ //tried using a preexisting username
				out.println("<body onload=directToEdit(\"?"
					+ "username=" + request.getParameter("username")
					+ "&password=" + request.getParameter("password")
					+ "&email=" + request.getParameter("email")
					+ "&groups=" + request.getParameter("groups")
					+ "&oldUsername=" + request.getParameter("oldUsername")
					+ "&loadCase=existent"
					+ "\")>Redirecting you to Edit User...</body></html>");
			} else {//Username did not change
				//update tables
				String pwd = null;
                                if (request.getParameter("passFlag").equals("true")) {
                                    pwd = HashPassword(request.getParameter("password"));
                                } else {
                                    pwd = request.getParameter("password");
                                }
				DBConnect.updateSQL("USERS",new String[]{ "password" }, new String[] { pwd },"username",request.getParameter("username"));
				DBConnect.updateSQL("USER_INFO",new String[]{ "email" }, new String[] { request.getParameter("email") },"username",request.getParameter("username"));
				DBConnect.deleteSQL("USER_ROLES","username",request.getParameter("username"));

//ADDED-------------------------------------------------------------------------
				//makeGroups(request,DBConnect);
				manageGroups(request,DBConnect);
//-------------------------------------------------------------------------
				out.println("<body><h3>User '"+ request.getParameter("username") +"' successfully modified!</h3>");
				out.println("<a href=\"ListUsers\">Return to User Listing</a></body></html>");
			}
		} catch (NullPointerException npe) {
			//add new user stuff
			in = new String[]{ (request.getParameter("username")),(request.getParameter("password")) };
			String[] params = {"username","password"};
			DBConnect.insertSQL("USERS",params,in);

			in = new String[] {request.getParameter("username"),request.getParameter("email")};
			params[1] = "email";
			DBConnect.insertSQL("USER_INFO",params,in);

			//insert groups
//ADDED-------------------------------------------------------------------------
			manageGroups(request,DBConnect);
//-------------------------------------------------------------------------

			//drop all old user stuff
			String oldUsername = request.getParameter("oldUsername");
			DBConnect.deleteSQL("USER_INFO","username",oldUsername);
			DBConnect.deleteSQL("USER_ROLES","username",oldUsername);
			DBConnect.deleteSQL("USERS","username",oldUsername);

//ADDED-------------------------------------------------------------------------
			String SQL = "UPDATE chatUsers SET removed = 0 WHERE username = ?";
			DBConnect.freeformSQL(SQL,new String[]{oldUsername});
//-------------------------------------------------------------------------

			out.println("<body><h3>User '"+ request.getParameter("username") +"' was successfully modified!</h3>");
			out.println("<a href=\"ListUsers\">Return to User Listing</a></body></html>");
		}
                finally
                {
                    DBConnect.CleanUp();
                }
	}

//UPDATED-------------------------------------------------------------------------
	//returns whether or not chat was found in the groups this user is supposed to have
	private boolean makeGroups(HttpServletRequest request, DatabaseConnector DBConnect){
		String reqGroups = request.getParameter("groups");
		String[] in;
		boolean chat = false;
		if (!reqGroups.equals("")) {
			String[] groups = reqGroups.split(";");
			for (int i=0;i<groups.length;i++){
				if (groups[i].equals("chat")) chat = true;
				in = new String[]{ request.getParameter("username"),groups[i] };
				DBConnect.insertSQL("USER_ROLES",new String[] { "username","role" },in);
			}
		} return chat;
	}
//-------------------------------------------------------------------------

	public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
		doPost(request, response);
	}

//ADDED-------------------------------------------------------------------------
	public boolean isAChatUser(String username){
		String SQL = "SELECT username FROM chatUsers WHERE username=?";
		DatabaseConnector con = new DatabaseConnector(DatabaseConnector.getDatabaseType());
		String[][] rs = con.selectSQL(SQL,1,new Object[]{username});
		try{
			if (rs[0][0]!= null) { }//trigger
			return true;
		} catch (Exception e){
			return false;
		}
                finally
                {
                    con.CleanUp();
                }
	}

	public void manageGroups(HttpServletRequest request, DatabaseConnector DBConnect){
		if (makeGroups(request,DBConnect)==true){ //user is listed as having the chat group
			if (isAChatUser(request.getParameter("username"))){ //user is already in chatUsers
				String SQL = "UPDATE chatUsers SET removed = ? WHERE username = ?";
				DBConnect.freeformSQL(SQL,new Object[]{0,request.getParameter("username")});
			} else { //user needs to be added to chatUsers
				String SQL = "INSERT INTO chatUsers(username,chatID,removed) VALUES (?,?,?)";
				DBConnect.freeformSQL(SQL,new Object[]{request.getParameter("username"),0,0});
			}
		} else { //user is listed as not being in chat group
			if (isAChatUser(request.getParameter("username"))){ //user is already in chatUsers
				String SQL = "UPDATE chatUsers SET removed=? WHERE username = ?";
				DBConnect.freeformSQL(SQL,new Object[]{1,request.getParameter("username")});
			} //otherwise, user is not in chatUsers and should not be in it
		}
	}

    private String HashPassword(String p)
    {
        String hp = "";
        try
        {
            MessageDigest m=MessageDigest.getInstance("MD5");
            byte[] data = p.getBytes();
            m.update(data, 0, data.length);
            BigInteger i = new BigInteger(1,m.digest());
            hp = String.format("%1$032X", i);
            return hp;

        }
        catch (Exception e)
        {
            System.out.println(e.getClass()+ ", " + e.getMessage());
        }
        return hp;
    }
}
//-------------------------------------------------------------------------